<?php
declare (strict_types = 1);

namespace app\admin\controller;

use think\Exception;
use think\exception\ValidateException;
use think\facade\Log;
use think\response\Json;

class ProductSpecValue extends Base{

    public function getList() : Json {
        $data["spec_id"] = $this->request->param("spec_id", 0, "intval");
        try{
            validate(\app\admin\validate\ProductSpecValue::class)->scene("get_list")->check($data);
        }catch (ValidateException $e){
            return show(config("status.error"), $e->getMessage());
        }

        $specValues = [];

        try{
            $specValues = (new \app\business\ProductSpecValue())->getList($data["spec_id"]);
        }catch (Exception $e){
            Log::error($e->getMessage());
            return show(config("status.error"), "获取属性值列表失败");
        }

        return show(config("status.success"), "ok", $specValues);

    }

    public function save() : Json {
        $data["spec_id"] = $this->request->param("spec_id", 0, "intval");
        $data["name"] = $this->request->param("name", "", "trim");

        try{
            validate(\app\admin\validate\ProductSpecValue::class)->scene("save")->check($data);
        }catch (ValidateException $e){
            return show(config("status.error"), $e->getMessage());
        }

        try{
            $data["operate_user"] = $this->admin["username"];
            $result = (new \app\admin\business\ProductSpecValue())->save($data);
            if (!$result) {
                return show(config("status.error"), "保存失败");
            }
        }catch (Exception $e){
            return show(config("status.error"), $e->getMessage());
        }

        return show(config("status.success"), "保存成功");
    }
}